package com.ys.controller.api.storage;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.storage.TccAllocateDetail;
import com.ys.mapper.storage.StorageMapper;
import com.ys.util.shiro.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.storage.TccStockControl;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/api/inter/tccStockControl")
public class ApiInterTccStockControlController {

	private static final Logger logger = LoggerFactory.getLogger(ApiInterTccStockControlController.class);

	@Autowired
	private CommonApiService<TccStockControl> commonApiService;

	@Autowired
	private StorageMapper storageMapper;

	@RequiresPermissions("tccStockControl:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TccStockControl cond, String conditions){
		
        cond = setSeachSql(cond, conditions);
		LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
		//合计
		{
			JSONObject JO = new JSONObject();
			// 合计
			JO.put("productNum", cond.setFields("ISNULL(SUM(A.productNum),0)").sumDecimal());
			JO.put("productNumAll", cond.setFields("ISNULL(SUM(A.productNumAll),0)").sumDecimal());
			tableVoJA.setTotalRow(JO);
		}
		return tableVoJA;
	}
	
	@RequestMapping("/searchForModal")
    @ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute TccStockControl cond,String vgsbm,String productCode,String cck,Long allocateDetailId){
		
		cond.where("A.ProductNum > 0");
		cond.addField("DATEDIFF(day, A.Drksj, getdate()) kcdays");
		//权限
		if (vgsbm != null && productCode != null&& cck != null){
			cond.addLeftJoin("TCC_Location B ON A.chw = B.chw");
			cond.addLeftJoin("TCC_WarehouseArea C ON C.ckq = B.ckq");
			cond.where("  A.productCode = '" + productCode + "'" + " AND A.vgsbm = '" + vgsbm + "'" + " AND C.cck = '" + cck + "'");
			cond.addField("(SELECT tss.AssembleBid FROM TCC_StockControl tsc LEFT JOIN TCC_StockControlRunning tsr ON tsr.StockControlId = tsc.id LEFT JOIN TCC_StockSource tss ON tss.StockControlRunningId = tsr.id WHERE tsc.id = A.id AND tss.IsNewInventory = 1 AND tss.AssembleBid IS NOT NULL) bidProductAssemble");
        	if (allocateDetailId != null){
				Map<String,Object> extraParam = new TccAllocateDetail()
						.addLeftJoin("TCC_Allocate B ON B.bid = A.bidAllocate")
						.addField("B.type")
						.where("A.id = " + allocateDetailId)
						.queryFirstMap();
				if (extraParam.get("type").toString().equals("2")){
					cond.addField(extraParam.get("singlePrice") + " purchasePriceAll");
				}else {
					cond.addField( "A.purchasePrice purchasePriceAll");
				}
			}
		}
		return commonApiService.searchLay(cond);
	}

	@RequiresPermissions("tccStockControl:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccStockControl cond, String conditions) throws Exception{
		
        cond = setSeachSql(cond, conditions);
		
		cond.setPage(0).setSize(99999);
		
		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCC_StockControl)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
        ExportExcelUtils<TccStockControl> util = new ExportExcelUtils<TccStockControl>(new TccStockControl());
        
        String toFilePath = util.exportExcel(listData, listField, "库存管理");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     */
    private TccStockControl setSeachSql(TccStockControl cond, String conditions){
		
		String _ys_numType = ConditionUtil.getConditionValue(conditions, "_ys_numType");
		if (_ys_numType != null && _ys_numType.length() > 0) {
			if ("1".equals(_ys_numType)) {
				cond.where("A.ProductNumAll = 0");
			} else if ("2".equals(_ys_numType)) {
				cond.where("A.ProductNumAll != 0");
			}
		}
		
		cond.addField("DATEDIFF(day, A.Drksj, getdate()) kcdays");
		
		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid = A.CompanyVid")
			.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm = A.Vgsbm")
			.addField("B.Vname companyVname,C.CUser operatorUserId,");
		
		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_StockControl, cond);
        return  cond;
    }




    //库存管理（手工组装调用）
	@RequestMapping("/searchForModalByTccAssembleByHand")
	@ResponseBody
	public LayuiTableVoJA searchForModalByTccAssembleByHand(Model model, HttpServletRequest request, HttpServletResponse response,
										 @ModelAttribute TccStockControl cond, String conditions){

		cond.where("A.ProductNum > 0");

		String _ys_subCode = ConditionUtil.getConditionValue(conditions, "_ys_subCode");//子件编码
		if (_ys_subCode != null) {
			cond.where("A.ProductCode ='" + _ys_subCode + "'");
		}
		cond.addField("A.ProductCode AS _ys_subCode");

		cond.addLeftJoin("TCC_Location SD ON SD.Chw = A.Chw")//货位信息表
				.addField("SD.Vhw AS subVhw")//货位
				.addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
				.addField("SE.Vkq AS subVkq")//库区
				.addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
				.addField("SF.Vck AS subVck")//仓库

		.setIsParent(0)
		;


		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid = A.CompanyVid")
				.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm = A.Vgsbm")
				.addField("B.Vname companyVname,C.CUser operatorUserId");

		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_StockControl, cond);
		return commonApiService.searchLay(cond);
	}




	//库存管理（手工拆装单调用）
	@RequestMapping("/searchForModalByDisassembleByHand")
	@ResponseBody
	public LayuiTableVoJA searchForModalByDisassembleByHand(Model model, HttpServletRequest request, HttpServletResponse response,
										 @ModelAttribute TccStockControl cond){
		cond.addLeftJoin("TCC_Location SD ON SD.Chw = A.Chw")//货位信息表
				.addField("SD.Vhw AS vhw")//货位
				.addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
				.addField("SE.Vkq AS vkq")//库区
				.addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
				.addField("SF.Vck AS vck")//仓库

				.where("A.Chw IS NOT NULL")
				.setIsParent(1)
		;
		cond.where("A.ProductNum > 0");
		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid = A.CompanyVid")
				.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm = A.Vgsbm")
				.addField("B.Vname companyVname,C.CUser operatorUserId");

		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_StockControl, cond);
		LayuiTableVoJA res = commonApiService.searchLay(cond);

		return res;
	}


	//库存管理（调取子件库存信息）
	@RequestMapping("/searchForModalBySub")
	@ResponseBody
	public LayuiTableVoJA searchForModalBySub(Model model, HttpServletRequest request, HttpServletResponse response,
															@ModelAttribute TccStockControl cond){

		cond.addField("A.Id AS stockControlIdByOld");//库存调拨单用
		cond.addField("A.Vgsbm AS vgsbmByOld");//库存调拨单用
		cond.addField("A.Id AS stockControlIdByNewTxt");//库存调拨单用
		cond.addField("0 AS allocateNum");//库存调拨单用
		cond.addField("A.ProductName AS subName");//库存调拨单用
		cond.addField("A.ProductCode AS subCode");//库存调拨单用

		cond.addLeftJoin("TCC_Location SD ON SD.Chw = A.Chw")//货位信息表
				.addField("SD.Vhw AS vhw")//货位
				.addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
				.addField("SE.Vkq AS vkq")//库区
				.addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
				.addField("SF.Vck AS vck")//仓库

				.addLeftJoin("TP_ProductBasisComponent SB ON SB.Code = A.ProductCode")//listing库子件信息
				.addField("SB.SubCodeMerge AS subCodeMerge")//子件合并编码

				//.addLeftJoin("TP_ProductActive PA ON PA.Code = A.ProductCode")
				//.addField("CASE WHEN A.IsParent = 0 NULL  THEN SB.SubCodeMerge ELSE PA.CodeMerge END  subCodeMerge")


				.addLeftJoin("THR_OperateCompanyApply SG ON SG.Vgsbm = A.Vgsbm")
				.addField("SG.Vgsjc AS vgsjcByOld")//运营公司简称

				.addLeftJoin("TB_CompanyInfo SH ON SH.VId = A.CompanyVid")
				.addField("SH.Vname AS vname")//公司名称


				.where("A.Chw IS NOT NULL")
				.setIsParent(0)
		;
		cond.where("A.ProductNum > 0");

		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid = A.CompanyVid")
				.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm = A.Vgsbm")
				.addField("B.Vname companyVname,C.CUser operatorUserId");


		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_StockControl, cond);
		return commonApiService.searchLay(cond);
	}




	//库存管理 -  库存调拨单
	@RequestMapping("/searchForModalByAllocate")
	@ResponseBody
	public LayuiTableVoJA searchForModalByAllocate(Model model, HttpServletRequest request, HttpServletResponse response,
											  @ModelAttribute TccStockControl cond){
		cond.addField("A.Id AS controlId");//库存出库单用
		cond.addField("A.Id AS stockControlIdByOld");//库存调拨单用
		cond.addField("A.Vgsbm AS vgsbmByOld");//库存调拨单用
		cond.addField("A.Id AS stockControlIdByNewTxt");//库存调拨单用
		cond.addField("0 AS allocateNum");//库存调拨单用
		cond.addField("A.ProductName AS subName");//库存调拨单用
		cond.addField("A.ProductCode AS subCode");//库存调拨单用

		cond.addLeftJoin("TCC_Location SD ON SD.Chw = A.Chw")//货位信息表
				.addField("SD.Vhw AS vhw")//货位
				.addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
				.addField("SE.Vkq AS vkq")//库区
				.addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
				.addField("SF.Vck AS vck")//仓库

				.addLeftJoin("TP_ProductBasisComponent SB ON SB.Code = A.ProductCode")//listing库子件信息
				//.addField("SB.SubCodeMerge AS subCodeMerge")//子件合并编码

				.addLeftJoin("TP_ProductActive PA ON PA.Code = A.ProductCode")
				.addField("CASE WHEN A.IsParent = 0 THEN SB.SubCodeMerge ELSE PA.CodeMerge END  subCodeMerge")

				.addField("DATEDIFF(day, A.Drksj, getdate()) kcdays")
				.addLeftJoin("THR_OperateCompanyApply SG ON SG.Vgsbm = A.Vgsbm")
				.addField("SG.Vgsjc AS vgsjcByOld")//运营公司简称
				.addField("SG.VGsSh AS vgsShByOld")//运营公司税号

				.addLeftJoin("TB_CompanyInfo SH ON SH.VId = A.CompanyVid")
				.addField("SH.Vname AS vname")//公司名称
				.addField("A.RkBid sourceBid")//来源单号(组装)


				.where("A.Chw IS NOT NULL")
		//.setIsParent(0)
		;
		cond.where("A.ProductNum > 0");

		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid = A.CompanyVid")
				.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm = A.Vgsbm")
				.addField("B.Vname companyVname,C.CUser operatorUserId");



		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_StockControl, cond);
		return commonApiService.searchLay(cond);
	}



	/**
	 * 加载库存信息
	 */
	@RequestMapping("/searchZy")
	@ResponseBody
	public LayuiTableVoJA searchZy(Model model, HttpServletRequest request, HttpServletResponse response,
											  @ModelAttribute TccStockControl cond) {

		cond.addField("A.Id AS stockControlBeforeId");//货位转移单用
		cond.addField("(select TOP 1 C.assembleBid AS assembleBid  from TCC_StockControlRunning B  left join TCC_StockSource C on C.StockControlRunningId = B.id where B.StockControlId = A.id AND C.IsNewInventory = 1) assembleBid");//组装单号

		cond.addLeftJoin("TCC_Location SD ON SD.Chw = A.Chw")//货位信息表
				.addField("SD.Vhw AS vhwYc")//货位
				.addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
				.addField("SE.Vkq AS vkqYc")//库区
				.addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
				.addField("SF.Vck AS vckYc")//仓库

			.addLeftJoin("TP_ProductActive B on A.productCode = B.Code")
				.addField("B.CodeMerge codeMerge")

		   		.addField("DATEDIFF(day, A.Drksj, getdate()) kcdays")
				.addLeftJoin("TB_CompanyInfo SH ON SH.VId = A.companyVid")
				.addField("SH.Vname AS companyName")//公司名称
		.where("A.productNum > 0  AND A.Chw IS NOT NULL")
		;
		return commonApiService.searchLay(cond);
	}

	/**
	 * FBA计划调用库存
	 */
	@RequestMapping("/searchFbaPlan")
	@ResponseBody
	public LayuiTableVoJA searchFbaPlan(Model model, HttpServletRequest request, HttpServletResponse response,
								   @ModelAttribute TccStockControl cond,String cck,String vgsbm,Long shopId, String conditions) {
		LayuiTableVoJA vo = new LayuiTableVoJA();
		try {
			Integer page = cond._ys_page - 1;
			Integer size = cond._ys_size;

			String commodityCode = ConditionUtil.getConditionValue(conditions, "commodityCode");
			String commodityName = ConditionUtil.getConditionValue(conditions, "commodityName");

			List<Map<String, Object>> stockControlList = storageMapper.searchStockControlList(vgsbm,shopId,cck,commodityCode,commodityName,page,size);
			Integer count = storageMapper.countStockControlList(vgsbm,shopId,cck,commodityCode,commodityName,page,size);
			vo.setRowsByListMap(stockControlList);
			vo.setCount(count);

			return vo;
		} catch (Exception e) {
			vo.setCode(1);
			vo.setMsg("查询错误!");
			logger.error("FBA计划单调用库存信息失败="+e.getMessage());
			return vo;
		}
	}
}
